package com.sto.stoapp.activity.sales;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoScanAssignPieceActivity;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.camera.CameraActivity;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.BillPaymentEntity;
import com.sto.stoapp.entity.CameraEntity;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.manager.UnSentPictureManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.HelpGetPaymentThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

/**
 * 拍照签收
 * 
 * @author Administrator
 * 
 */
public class SalesSignPiecePhotoActivity extends StoListenerActivity {
	private StoHhmEditText cause;
	private Button select;

	private DataBusinessEntity dataBusiness;
	private String busiType = HomeBroadAction.AVIATION_SCANNER_BROAD;

	// private List<EditText> edit = new ArrayList<EditText>();
	private String CauseName = "";

	private final int CAMERA_RESULT = 0xf;

	private final int AUTOGRAPH_RESULT = 0xfe;

	private Button photograph, savePicture;

	private ImageView scanImage;

	private Bitmap mBitmap;

	private PopupWindow popupWindow;

	private Handler mHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what){
				case HelpGetPaymentThread.MSG_WHAT:

					Helper.showWaitePaySound(SalesSignPiecePhotoActivity.this);
					BillPaymentEntity entity= (BillPaymentEntity) msg.obj;

					ScanOff();
					final BaseDialog filterDialog=new BaseDialog(SalesSignPiecePhotoActivity.this);
					filterDialog.setTitles("此单号【" + entity.getBillNo() + "】为代收货款单号，代收金额为：【￥"+Double.valueOf(entity.getBillPayment())+"】。请注意代收！");
					filterDialog.show();
					filterDialog.getvCanncel().setVisibility(View.GONE);
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					break;
			}

			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sign_piece_photo);
		Bundle extras = getIntent().getExtras();
		busiType = extras.getString("busiType");
		this.setTitleBottom(R.string.more_sign_photo, busiType);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		/*
		 * 添加航空扫描员-问题件
		 * 
		 * @修改人：mgf
		 */
		// 航空-扫描-留仓件
		// if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
		// initScanRecordAdapter(TABLE_NAME_STATUS.STATUS_TABLE_AVIATION_PROBLEM);
		// } else {
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
		// }

	}

	private void initWidget() {
		code = (StoHhmEditText) this.findViewById(R.id.sign_odd_numbers_text);
		cause = (StoHhmEditText) this.findViewById(R.id.autograph_text);
		select = (Button) this.findViewById(R.id.select_autograph);

		scanImage = (ImageView) findViewById(R.id.scan_image);
		photograph = (Button) findViewById(R.id.photograph);
		savePicture = (Button) findViewById(R.id.save_picture);
		cause.setInputType(InputType.TYPE_CLASS_TEXT);
		addUploadTable(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
		// edit.add(code);
	}

	/**
	 * 监听控件
	 */
	private void initListen() {
		cause.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@SuppressLint("NewApi")
			@Override
			public void onEditClickListener(View v) {
				if (!cause.getText().toString().isEmpty()) {
					code.requestFocus();
				} else {
					cause.showSRF();
				}

			}
		});

		// cause.setOnClickListener(new StoOnClickListener(this) {
		// @Override
		// public void mHonClick(View v) {
		// SelectAutograph();
		// }
		// });

		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				cause.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().toString().length() == 0) {
					Helper.showSoundToast(SalesSignPiecePhotoActivity.this,
							getString(R.string.code_empty), false);
				} else {
					onScanResults(code.getText().toString());
				}
			}
		});

		photograph.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(SalesSignPiecePhotoActivity.this,
						CameraActivity.class);
				startActivityForResult(intent, CAMERA_RESULT);
			}
		});

		scanImage.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				initPopWindow();
			}
		});

		savePicture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (CheckScanCode(code.getText().toString())) {
					processScanData();
				}
			}
		});

		select.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {

				SelectAutograph();

			}
		});

		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */

		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) {
		 * onScanResults(code.getText().toString()); } });
		 */
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;

		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			Helper.showSoundToast(SalesSignPiecePhotoActivity.this,
					getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		CauseName = cause.getText().toString();
		try {
			if (mBitmap == null) {
				Helper.showSoundToast(this,
						getString(R.string.please_pictures), false);
				return;
			}
			if (cause.getText().toString().isEmpty()) {
				// 原因不能为空
				SoundManager.getInstance(this).playFailureSound();
				Helper.showToast(this, "签名不能为空");
				cause.requestFocus();
				cause.setText("");
				return;
			}
			if (Chineselength(cause.getText().toString()) > 14) {
				Helper.showSoundToast(this, "签名过长,请减少签名长度!", false);
				cause.setText("");
				cause.requestFocus();
				// autograph.setSelection(autograph.length());
				// autograph.requestFocus();
				return;
			}
			if (!isChineseChar(cause.getText().toString())) {
				Helper.showSoundToast(this, "签名不能包含非法字符!", false);
				cause.setText("");
				cause.requestFocus();
				return;
			}
			if (!code.getText().toString().isEmpty()
					&& CauseName.equals(cause.getText().toString())) {

				//Add by wj过滤单号
				boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
				if(isFilter){
					showFilterDialog(code.getText().toString().trim());
					return;
				}
				//End by wj

				//代收货款校验
				int onOff=StoFilePreference.getInstance(this).getPayMentOnOff();
				if(1==onOff){
					String bill=code.getText().toString().trim();
					if("11".equals(bill.substring(0,2)) || "33".equals(bill.substring(0,2))){
						new HelpGetPaymentThread(bill,SalesSignPiecePhotoActivity.this,mHandler).start();
					}
				}
				//代收货款校验

				if (addPieceRecord()) {
					UnSentPictureManager.getInstance(this).addPictureCount();
					this.addCodeNumber();
					setSaveData(true);

					Helper.showSoundAndVibrator(this, true);
					// SoundManager.getInstance(this).playSuccessSound();
					addScanRecordInfo(code.getText().toString());
					// ticketNumber.setText(String.valueOf(++count));
					code.setSelection(code.length());

					// 保存图片
					if (mBitmap != null) {
						saveFile(mBitmap);
						mBitmap = null;
						code.setText("");
						code.requestFocus();
						scanImage.setImageResource(R.drawable.default_img);
					}
				}
				// 提示插入数据失败
				else {
					Helper.showSoundToast(this,
							getString(R.string.code_repeat), false);
				}

				ScanOpen();
			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord() {
		boolean ret;

		dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SALESMAN_SIGN
				.getOpCode());
		dataBusiness.setBar_code_number(code.getText().toString());

		dataBusiness.setCodeType(getExpType(code.getText().toString()));
		// 签收人
		dataBusiness.setRecv_person(cause.getText().toString());
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());

		// 网点名称
		dataBusiness.setSend_person(StoFilePreference.getInstance(this)
				.getSiteName());

		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(
				UnifiedStaticType.SIMPLE_DATE_FORMAT);
		String nowDate = format.format(date);
		dataBusiness.setUser_defined3(nowDate);
		// // 航空-扫描-问题件
		// if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
		// ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
		// TABLE_NAME_STATUS.STATUS_TABLE_AVIATION_PROBLEM);
		// addUploadTable(TABLE_NAME_STATUS.STATUS_TABLE_AVIATION_PROBLEM);
		// } else {
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_SALESMAN_SIGN);
		// }

		return ret;
	}
	/**
	 * 非法符号判断(只能字母,数字,中文)
	 * 
	 * @param content
	 * @return
	 */
	private boolean isChineseChar(String content) {
		Pattern p = Pattern.compile("^[\\w\\u4e00-\\u9fa5]+$");
		Matcher m = p.matcher(content);
		return m.matches();
	}

	private int Chineselength(String value) {
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
		for (int i = 0; i < value.length(); i++) {
			/* 获取一个字符 */
			String temp = value.substring(i, i + 1);
			/* 判断是否为中文字符 */
			if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
				valueLength += 2;
			} else {
				/* 其他字符长度为1 */
				valueLength += 1;
			}
		}
		return valueLength;
	}
	
	/**
	 * 选择列表返回的结果
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == AUTOGRAPH_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				cause.setText(courierEntity.getSelectName());
				cause.setSelection(cause.length());
				code.requestFocus();
				CauseName = courierEntity.getSelectName();
				// if (recvPresonCode.length() > 0)
				// destination.requestFocus();
			}
		} else if (requestCode == AUTOGRAPH_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			CauseName = "";
			cause.setText("");
			Helper.showSoundToast(this, getString(R.string.undefined), false);
		} else if (requestCode == CAMERA_RESULT
				&& resultCode == Activity.RESULT_OK) {
			CameraEntity entity = data.getParcelableExtra("bitmapPicture");
			if (entity != null) {
				mBitmap = entity.getDraw();
				scanImage.setImageBitmap(mBitmap);
				savePicture.requestFocus();
			}
			// ScanOpen();
		} else {

		}

	}

	/**
	 * 放大图片显示
	 */
	@SuppressWarnings("deprecation")
	private void initPopWindow() {
		if (mBitmap == null) {
			return;
		}
		Display display = getWindowManager().getDefaultDisplay();
		// 加载popupWindow的布局文件
		View contentView = LayoutInflater.from(this).inflate(
				R.layout.sto_picture_popup, null);
		// 设置popupWindow的背景颜色
		contentView.setBackgroundColor(Color.BLACK);
		// 声明一个弹出框
		popupWindow = new PopupWindow(contentView, LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAtLocation(code, Gravity.CENTER_VERTICAL, 0, 0);
		final ImageView imageView = (ImageView) contentView
				.findViewById(R.id.dis_picture);
		int width = display.getWidth() - 50;
		int height = display.getHeight() - 50;
		// 将图片设置为宽，高，在这儿就可以实现图片的大小缩放
		Bitmap resize = Bitmap.createScaledBitmap(mBitmap, width, height, true);
		// Matrix m = new Matrix();
		// m.setRotate(90); // 逆时针旋转15度
		// // 做好旋转与大小之后，重新创建位图，0-width宽度上显示的区域，高度类似
		// Bitmap b = Bitmap.createBitmap(resize, 0, 0, height, width, m, true);
		// 显示图片
		imageView.setImageBitmap(resize);
		imageView.setFocusableInTouchMode(true);
		imageView.requestFocus();

		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				closePopupWindow();
			}
		});

		imageView.setOnKeyListener(new OnKeyListener() {

			@SuppressWarnings("static-access")
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == event.KEYCODE_BACK) {
					closePopupWindow();
				}
				return false;
			}
		});

	}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	@SuppressLint({ "SimpleDateFormat", "NewApi" })
	private boolean saveFile(Bitmap bm) throws IOException {
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(
				UnifiedStaticType.SIMPLE_DATE_FORMAT);
		String nowDate = format.format(date);
		String simpleDate = nowDate.replace("-", "");
		String dirPath = Environment.getExternalStorageDirectory().toString()
				+ UnifiedStaticType.QS_IMAGE_PATH + simpleDate + "/";

		File dirFile = new File(dirPath);// 新建目录
		if (!dirFile.exists()) {// 判断文件夹目录是否存在
			dirFile.mkdirs();// 如果不存在则创建
		}
		// String filename = code.getText().toString() + "-" + simpleDate +
		// ".jpg";
		String filename = code.getText().toString() + ".jpg";
		String filePath = dirPath + filename;

		BufferedOutputStream fOut = new BufferedOutputStream(
				new FileOutputStream(filePath));

		// OutputStream fOut = new FileOutputStream(filePath);
		bm.compress(Bitmap.CompressFormat.JPEG, 80, fOut);
		fOut.flush();
		fOut.close();

		// 保存图片路径
		StoDataBaseOperation.getInstance(this).updatePicturePath(
				EnumTableNames.STATUS_TABLE_SALESMAN_SIGN.getTableName(),
				filePath, code.getText().toString(),
				EnumTableNames.STATUS_TABLE_SALESMAN_SIGN.getOpCode());

		return true;
	}

	/**
	 * 选择签名
	 */
	private void SelectAutograph() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (cause.getText().length() == 0) {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_SIGN_INFO_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_SIGN_INFO_LIKE);
				tableParcel.setSelectField(new String[] { "%"
						+ cause.getText().toString() + "%" });
			}
			tableParcel.setSelectCode("shortKey");
			tableParcel.setSelectName("nameValue");

			Intent intent = new Intent(SalesSignPiecePhotoActivity.this,
					StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, AUTOGRAPH_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("SelectAutograph", e.getMessage());
		}
	}

	private void closePopupWindow() {
		if (popupWindow != null) {
			popupWindow.dismiss();
			popupWindow = null;
		}
	}

	private void exitShuRuFa() {
		InputMethodManager imm = (InputMethodManager) cause.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		imm.hideSoftInputFromWindow(cause.getWindowToken(), 0);
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		// exitShuRuFa();
		showNotice();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			code.setText("");
			code.setText(result);
			code.setSelection(code.length());
			photograph.requestFocus();
			if (CheckScanCode(result)) {
				Helper.showSoundAndVibrator(SalesSignPiecePhotoActivity.this,
						true);
			}
			// if (CheckScanCode(result)) {
			// processScanData();
			// }
			// code.setText("");
		}

	}
}
